package com.zhangfei.order.biz.third;

import com.zhangfei.order.biz.domain.dto.ProductInfoDTO;
import com.zhangfei.product.proto.product1.ProductServer;
import com.zhangfei.product.proto.product1.ProductServiceGrpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 调用第三方的服务
 */
@Slf4j
@Service
public class ProductGrpcClient {

    @Resource
    private ProductServiceGrpc.ProductServiceBlockingStub productService;

    /**
     * 访问商品服务，查询商品
     */
    public ProductInfoDTO queryProduct(String productId) throws Exception {
        //1.构建请求参数
        ProductServer.QueryProductRequest request = ProductServer.QueryProductRequest
                .newBuilder()
                .setProductId(productId)
                .build();
        //2.远程调用：一般需要写一个aop，对于第三方的调用，请求和响应都需要打印参数，这样方便出现问题的时候，就知道是哪一个模块出现的问题
        log.info("ProductGrpcClient queryProduct request:{}",request);
        ProductServer.QueryProductResponse queryProductResponse = productService.queryProduct(request);
        log.info("ProductGrpcClient queryProduct response:{}",queryProductResponse);
        //3.判断请求是否成功
        if (queryProductResponse.getCode() != 200) {
            throw new Exception("请求失败");
        }

        //4.结果组装
        ProductServer.ProductInfo data = queryProductResponse.getData();
        return ProductInfoDTO.builder()
                .productId(data.getProductId())
                .productName(data.getProductName())
                .count(data.getCount())
                .model(data.getModel())
                .build();
    }


}
